package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiWXMain*
 * @Description:对接微信公众号主接口
 * @author: LJT* @date 2019-12-17 02:28:00
 *
 */

public class apiWXSendTemplate implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXSendTemplate.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) e.nextElement();
            //再通过request.getParameter("")的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        // 获取发送操作公众号类型
        String opsource = request.getParameter("opsource");
        log.debug("原始Get请求参数:" + opsource);

        // 发送报文信息
        String inData = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            inData += line;
        }
        log.debug("原始Post请求参数:" + inData);

        // 预定义返回出参
        JSONObject result = new JSONObject();
        JSONObject datamsg = new JSONObject();

        // 非空校验检查检查
        if (KHUtil.isNull(opsource) || KHUtil.isNull(inData)) {
            result.put("code", -1);
            result.put("msg", KHUtil.isNullMSG("opsource", opsource) + KHUtil.isNullMSG("inData", inData));
            return result.toString();

        } else {

            try {
                // 获取Token

                String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "NGS-Local");
                JSONObject apiTokenJson = JSONObject.parseObject(Util.doHttpGet(DOMAIN + "/ngsapitask/api/apiWXToken?opsource=" + opsource, "UTF-8", 5000, 0));
                String access_token = "";
                if (apiTokenJson.getInteger("code") == 1) {
                    access_token = apiTokenJson.getJSONObject("data").getString("access_token");
                } else {
                    return apiTokenJson.toString();
                }

                // 调用微信发送模板消息,公众号template 小程序subscribe
                String wxSendFlag = (opsource == "minip") ? "subscribe" : "template";
                String wxSendTemplateURL = "https://api.weixin.qq.com/cgi-bin/message/" + wxSendFlag + "/send?access_token=" + access_token;

                String wxSendTemplateResult = Util.doHttpPost(wxSendTemplateURL, inData, "UTF-8", 5000, 0);
                JSONObject wxSendTemplateJson = JSONObject.parseObject(wxSendTemplateResult);

                log.error("调用微信发送模板消息返回:" + wxSendTemplateResult);

                int errcode = wxSendTemplateJson.getInteger("errcode");
                String errmsg = wxSendTemplateJson.getString("errmsg");

                if (errcode != 0) {

                    result.put("code", errcode);
                    result.put("msg", errmsg);

                } else {
                    int msgid = wxSendTemplateJson.getInteger("msgid");

                    result.put("code", 1);
                    result.put("msg", "发送完成");
                    datamsg.put("msgid", msgid);
                    result.put("data", datamsg);
                }

            } catch (Exception e1) {
                log.error("接口处理异常", e1);

                result.put("code", -1);
                result.put("msg", e1.getMessage());
                result.put("data", datamsg);

            }
        }

        log.debug("发送公众号模板消息处理完成返回结果:" + result.toString());

        return result.toString();
    }

}
